//
//  CateTableViewController.swift
//  MeiTuan
//
//  Created by 傻先森cc on 2017/10/23.
//  Copyright © 2017年 ZSJ. All rights reserved.
//

import UIKit

let TAG_TITLE = 1
let TAG_ADDR = 2
let TAG_SALE = 3
let TAG_PIC = 4
let TAG_PRICE = 5


class CateTableViewController: UITableViewController {

    lazy var allArr:NSMutableArray = {
        () -> NSMutableArray in
        let tempallArr = NSMutableArray()
        //1.获取数据
        let strPath = Bundle.main.path(forResource:"Cate",ofType: "plist")
        //2.读取文件
        let arr: NSMutableArray = NSMutableArray(contentsOfFile: strPath!)!
        for dict in arr {
            let model: CateModel = CateModel.cateModelWithDict(dict as! NSDictionary)
            tempallArr.add(model)
        }
        return tempallArr
    }()
    var HeaderView = UIView()
    var scrollView = UIScrollView()
    var pageContorl = UIPageControl()
    
    var images = ["4.jpg","5.jpg","6.jpg","7.jpg"]
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title="美食团购"
        header()
    }
    
    func header(){
        let w = self.view.frame.size.width
        let h = self.view.frame.size.height
        HeaderView.frame = CGRect(x:0,y:0,width:w,height:h*2/6)
        self.tableView.tableHeaderView = HeaderView
        scrollView.frame = CGRect(x: 0, y: 0, width: w, height: h*2/6 - 20)
        scrollView.contentSize = CGSize(width: w*5,height: scrollView.frame.height)
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        HeaderView.addSubview(scrollView)
        //页面
        pageContorl.frame = CGRect(x: w*2/5, y: scrollView.frame.height, width: w*1/5, height:20)
        pageContorl.addTarget(self, action: #selector(pageChanged(_:)), for: UIControlEvents.valueChanged)
        pageContorl.numberOfPages = images.count
        pageContorl.pageIndicatorTintColor = UIColor.yellow
        pageContorl.currentPageIndicatorTintColor = UIColor.red
        pageContorl.currentPage = 0
        HeaderView.addSubview(pageContorl)
        
        for i in 1...self.images.count{
            let imageView = UIImageView(image: UIImage(named: images[i-1]))
            imageView.frame = CGRect(x: w*CGFloat(i), y: 0, width: w, height: scrollView.frame.height)
            scrollView.addSubview(imageView)
            scrollView.delegate = self
        
    }
        
        let imageView1 = UIImageView(image: UIImage(named: images.last!))
        imageView1.frame = CGRect(x: 0, y: 0, width: w, height: scrollView.frame.height)
        let imageView5 = UIImageView(image: UIImage(named: images.first!))
        imageView5.frame = CGRect(x: w * 4, y: 0, width: w, height: scrollView.frame.height)
        scrollView.addSubview(imageView1)
        scrollView.addSubview(imageView5)
        
        //设置viewdidiload时scrollView的位置
        scrollView.scrollRectToVisible(CGRect(x: w, y: 0, width: w, height: h), animated: false)
        //设置定时器
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AutoScroll), userInfo: nil, repeats: true)
    }
        
        
        override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            //计算是第几页
            let w = self.scrollView.frame.width
            let h = self.scrollView.frame.height
            
            let page = Int(scrollView.contentOffset.x / scrollView.frame.width)
            if page == 0 {
                self.scrollView.scrollRectToVisible(CGRect(x: CGFloat(images.count)*w, y: 0, width: w, height: h), animated: false)
                pageContorl.currentPage = 2
            }else if page == images.count + 1 {
                self.scrollView.scrollRectToVisible(CGRect(x: w, y: 0, width: w, height: h), animated: false)
                pageContorl.currentPage = 0
            }else {
                //设置pageControl的当前页，当paageControl.currentPage改变狗，会自动
                pageContorl.currentPage = page - 1
            }
        }

    
    
    func pageChanged(_ sender:UIPageControl) {
        let page = pageContorl.currentPage
        let p = CGFloat(page)
        let w = self.scrollView.frame.width
        scrollView.scrollRectToVisible(CGRect(x: p * w + w, y: 0, width: w, height: self.scrollView.frame.height), animated: false)
    }
    
    func AutoScroll(){
        var page = pageContorl.currentPage
        page = page + 1
        page =  page > 2 ? 0 : page//因为总共的索引为0,1,2
        pageContorl.currentPage = page
        pageChanged(pageContorl)
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1//有一组，且tableView方法就被调用1次
    }
 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.allArr.count//有四行
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        indexPath.section//组号
//        indexPath.row//行号
        
//        let cell = tableView.dequeueReusableCell(withIdentifier: "meiTuanCell", for: indexPath)//找模板
        let cell=MeiTuanCell.createCell(tableView: tableView)
        cell.model = self.allArr[indexPath.row] as! CateModel
        
//        cell.imageView?.image=UIImage(named: model.pic as String)
//        cell.textLabel?.text="\(model.name as String)"
        
//        let title = cell.viewWithTag(1) as! UILabel
//        let addr = cell.viewWithTag(2)as! UILabel
//        let sale = cell.viewWithTag(3)as! UILabel
//        let pic = cell.viewWithTag(4)a   s! UIImageView
//        let price = cell.viewWithTag(5)as! UILabel
//        
//        title.text="\(model.name as String)"
//        addr.text="地址：\(model.addr as String)"
//        sale.text="已售：\(model.sale as String)"
//        pic.image=UIImage (named:model.pic as String)
//        price.text="\(model.price as String)元"
        
        return cell
    }
 
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    //第一种跳转
//    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        //找下一个页面对应的类
//        let detail:detalViewController = storyboard?.instantiateViewController(withIdentifier: "detailView") as! detalViewController
//        let model:CateModel = self.allArr[indexPath.row] as! CateModel
//        //传递数据
//        detail.model=model
//        //显示detail页面
//        self.navigationController?.pushViewController(detail, animated: true)
//        
//    }
    
    //第二种跳转
        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let model: CateModel = self.allArr[indexPath.row] as! CateModel
            self.performSegue(withIdentifier: "toDetail", sender: model)
        }
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let detail:detailViewController = segue.destination as! detailViewController
            detail.model = sender as! CateModel
        }
        override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return "欢迎来到选购"
        }
        override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
            return "一共有\(allArr.count)种商品"
        }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
     Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
             Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
             Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    }
